import React, {FC, useContext, useEffect, useRef} from 'react';
import {Button, Divider, Flex, Form, Input, InputRef, message, Typography} from "antd";
import {MailOutlined} from "@ant-design/icons";
import {CommonRegex, KfInput, KfQuickForm} from "kf-web-library";
import {useRequest} from "ahooks";
import {SendVerificationCode} from "@/services";
import * as API from "@/services";
import lodash from "lodash";
import {FormattedMessage, useModel} from "@@/exports";
import KfCountdownButton from "@kf-web-library/components/es/KfCountdownButton/KfCountdownButton";
import {useIntl} from "umi";
import {HxConfigContext} from "@/layouts/HxConfigContext";

interface MobileModifyFormProps {
}

const MobileModifyForm: FC<MobileModifyFormProps> = (props) => {
  const {initialState} = useModel('@@initialState');
  const userInfo = initialState?.currentUserInfo;
  const {isZhCN} = useContext(HxConfigContext)
  const [form] = Form.useForm();
  const intl= useIntl();
  const oldVCodeInputRef = useRef<InputRef>(null);
  const newVCodeInputRef = useRef<InputRef>(null);

  const sendVerificationCodeReq = useRequest((
      p: SendVerificationCode,
      fillName: string,
      inputRef?: React.RefObject<InputRef>
    ) =>
      API.sendVerificationCode(p),
    {
      manual: true,
      onError: (e: any, p) => {
        if (e?.response?.data?.bizcode == 409011) {
          p[2]?.current?.focus?.();
        }
      },
      onSuccess: (resp, p) => {
        if (resp.flag) {
          if (lodash.isString(resp.data)) {
            //测试环境, 验证码会直接返回出来, 这里回填回去
            form.setFieldValue(p[1], resp.data)
          }
          message.success(<>已发送至<Typography.Text type="success">{p[0].emailOrMobile}</Typography.Text>，请注意接收</>);
        }
      }
    })

  useEffect(() => {
    form.setFieldValue("oldEmailOrMobile", userInfo?.phone)
  }, [userInfo]);


  return (
    <KfQuickForm
      formType={"mobileModify"}
      submitButtonText={<FormattedMessage id="text.submit"/>}
      formProps={{
        //layout: "vertical",
        form,
        className: "mobile-modify-form",
        labelCol: {
          flex: isZhCN ?'0 0 120px': '0 0 180px'
        },
        wrapperCol: {
          flex: "1"
        },

      }}
      submitRequest={{
        mobileModify: (formValues) => {
          return API.changePhone({
            ...formValues,
          })
        }
      }}
    >
      {
        userInfo?.phone && (
          <>
            <Form.Item
              label={<FormattedMessage id="text.current-mobile"/>}
              name="oldEmailOrMobile"
              rules={[
                {required: true},
                {
                  pattern: CommonRegex.CHINA_MOBILE_NUMBER_REGEX,
                  message: intl.formatMessage({id: "validation.mobile_require"}),
                }
              ]}
            >
              <KfInput size={"large"} readonly={true}/>
            </Form.Item>
            <Form.Item
              label={
                <FormattedMessage id="text.sms-verification-code"/>
              }
              required
            >
              <Flex vertical={false} gap={6}>
                <Form.Item
                  name="oldVerificationCode"
                  help=""
                  noStyle
                  hasFeedback={true}
                  rules={[{required: true, message: `请输入收到的短信验证码`}]}
                >
                  <Input ref={oldVCodeInputRef} maxLength={6} size={"large"} placeholder={`请输入收到的短信验证码`}/>
                </Form.Item>

                <KfCountdownButton
                  color="primary"
                  variant="filled"
                  size={"large"}
                  style={{width: 160, fontSize: 16}}
                  onClick={() => {
                    const oldMobile = form.getFieldValue("oldEmailOrMobile");
                    const captcha = form.getFieldValue("oldVerificationCode");
                    if (!oldMobile) {
                      message.error("请先输入手机号");
                      return;
                    }
                    return new Promise((resolve, reject) => {
                      sendVerificationCodeReq.runAsync({
                        emailOrMobile: oldMobile,
                        captcha,
                        verificationCodeType: "OLD_VERIFICATION_CODE_SMS",
                      }, "oldVerificationCode", oldVCodeInputRef).then(resp => {
                        return resp.flag ? resolve() : reject()
                      }).catch((error) => {
                        reject();
                        form.setFieldValue("oldVerificationCode", "")
                        oldVCodeInputRef.current?.focus?.();
                      });
                    });
                  }}
                >
                  <FormattedMessage id="text.send-verification-code"/>
                </KfCountdownButton>
              </Flex>
            </Form.Item>
            <Divider />
          </>
        )
      }

      <Form.Item
        label={<FormattedMessage id="text.new-mobile"/>}
        name="emailOrMobile"
        rules={[{required: true}]}
        style={{marginTop: 32}}
      >
        <KfInput size={"large"}/>
      </Form.Item>
      <Form.Item
        label={<FormattedMessage id="text.sms-verification-code"/>}
        required
      >
        <Flex vertical={false} gap={6}>
          <Form.Item
            name="newVerificationCode"
            help=""
            noStyle
            hasFeedback={true}
            rules={[{required: true, message: `请输入收到的短信验证码`}]}
          >
            <Input ref={newVCodeInputRef} size={"large"} placeholder={`请输入收到的短信验证码`}/>
          </Form.Item>

          <KfCountdownButton
            color="primary"
            variant="filled"
            size={"large"}
            style={{width: 160, fontSize: 16}}
            onClick={() => {
              const newMobile = form.getFieldValue("emailOrMobile");
              if (!newMobile) {
                message.error("请先输入邮箱号");
                return;
              }
              return new Promise((resolve, reject) => {
                sendVerificationCodeReq.runAsync({
                  emailOrMobile: newMobile,
                  verificationCodeType: "NEW_VERIFICATION_CODE_SMS",
                }, "newVerificationCode", newVCodeInputRef).then(resp => {
                  return resp.flag ? resolve() : reject()
                }).catch((error) => {
                  reject();
                  form.setFieldValue("newVerificationCode", "")
                  newVCodeInputRef.current?.focus?.();
                });
              });
            }}
          >
            <FormattedMessage id="text.send-verification-code"/>
          </KfCountdownButton>
        </Flex>
      </Form.Item>
    </KfQuickForm>
  );
};

export default MobileModifyForm;
